package com.example.testcookie;

import org.springframework.boot.configurationprocessor.json.JSONObject;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 * @author : championjing
 * @ClassName: LoginCtrl
 * @Description: TODO
 * @Date: 2020-11-22 13:33
 */
@RestController
public class LoginCtrl {
    
    @GetMapping("/login")
    public String login(@RequestParam String username,
                            HttpServletResponse response,
                            HttpServletRequest request){
        HttpSession session = request.getSession();
        
        User user = null;
        if (session != null) {
            user = (User) session.getAttribute("user");
            if ( user != null ) {
                System.out.println( user.getUsername() );
                return  "已有session";
            } else {
                System.out.println("user wei kong");
            }
        } 
        Cookie cookie=new Cookie("JSESSIONID", session.getId());
        //设置cookie保存时间
        cookie.setMaxAge(60*20);
        //被创建的cookie返回浏览器
        response.addCookie(cookie); 
        
        user = new User();
        user.setUsername( username );
        session.setAttribute( "user", user );
        
        return  "没有session"+session.getId();
    }
    
    @GetMapping("/user")
    public User getName(HttpServletRequest request){
        HttpSession session = request.getSession();
        User user = (User) request.getAttribute("user");
        return user;
    }
}
